import mitt from 'mitt'
import { message } from 'antd'
import { createHashHistory } from 'history'
import jsonrpc from './jsonrpc'

export const rpc = new jsonrpc()

export const bus = mitt()
export const history = createHashHistory()

export function proxyStorage(store) {
  return new Proxy(
    {},
    {
      set: (o, k, v) => (store[k] = JSON.stringify(v)),
      get: (o, k) => store[k] && JSON.parse(store[k]),
    }
  )
}

export const mem = proxyStorage({})
export const local = proxyStorage(localStorage)
export const session = proxyStorage(sessionStorage)

export function menuToTree(menu, id = 0) {
  return menu
    .sort((a, b) => a.orderNum - b.orderNum)
    .filter(v => v.parentId === id)
    .map(v => {
      const children = menuToTree(menu, v.menuId)
      return children.length ? { ...v, children } : v
    })
}

export function listToTree(list, id = null, keyId = 'id') {
  let rootIds = [id]
  if (id === null) {
    // detect rootId
    const listKeys = list.map(v => v[keyId])
    rootIds = list.filter(v => !listKeys.includes(v.parentId))
  }
  return list
    .filter(v => rootIds.includes(v.parentId))
    .map(v => {
      const children = listToTree(list, v[keyId], keyId)
      return children.length ? { ...v, children } : v
    })
}

export function checkres(res) {
  if (!res) {
    console.log('[CHECKRES]: Network error')
    return false
  }
  if (String(res) === '[object Promise]') {
    console.warn('[CHECKRES]: Maybe forget to await')
    return false
  }
  if (res.status !== 200) {
    console.log(`[CHECKRES]: ${res.status}`)
    return false
  }
  if (res.data?.code === 401) {
    return false
  }
  if (res.data?.code !== 1) {
    message.error('请求失败：' + res.data?.msg)
    return false
  }
  return true
}

export function checkresStatus(res) {
  if (!res) {
    console.log('[CHECKRES]: Network error')
    return false
  }
  if (String(res) === '[object Promise]') {
    console.warn('[CHECKRES]: Maybe forget to await')
    return false
  }
  if (res.status !== 200) {
    console.log(`[CHECKRES]: ${res.status}`)
    return false
  }
  if (res.data?.code === 401) {
    return false
  }
  if (res.data?.status.code !== '1') {
    message.error('请求失败：' + res.data?.status.msg)
    return false
  }
  return true
}

export function stripObjectEmpty(obj) {
  const out = {}
  Object.entries(obj).forEach(([key, value]) => {
    if (value || value === 0 || value === false) out[key] = value
  })
  return out
}

export function deepClone(obj) {
  let _obj = JSON.stringify(obj),
    objClone = JSON.parse(_obj)
  return objClone
}
